		//导入行政区域编码对应location_id映射表
		import location from './location.js';
		//全局变量
		var LOCATION_ID_USER = "000000000";
		var AD_CODE_USER = "000000";
		var keypool = [''];
		// var sunpool = [100, 101, 102, 103, 104, 150, 151, 152, 153];
		// var rainpool = [300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 350, 351, 399];
		// var snowpool = [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 456, 457, 499];
		// var smoggypool = [500, 501, 502, 503, 504, 507, 508, 509, 510, 511, 512, 513, 514, 515];
		var sunpool = ["100", "101", "102", "103", "104", "150", "151", "152", "153"];
		var rainpool = ["300", "301", "305", "306", "307", "308", "309", "310", "311", "312", "313", "314", "315", "316", "317", "318", "350", "351", "399"];
		var snowpool = ["400", "401", "402", "403", "404", "405", "406", "407", "408", "409", "410", "456", "457", "499"];
		var smoggypool = ["500", "501", "502", "503", "504", "507", "508", "509", "510", "511", "512", "513", "514", "515"];
		var thundpool = ["302","303","304"];
		
		
		var currentKey = getRandomKey();
		function getRandomKey(){
			if(keypool.length === 0){
				return 'Key Pool is Empty!';
			}
			let index = Math.floor(Math.random() * keypool.length);
			let key_user = keypool[index];
			currentKey = key_user;
			return key_user;
		}
		//获取并提取行政区域编码
		function QQmap(response) {
		    const result = response.result;
		    AD_CODE_USER = result.ad_info.adcode;
		    const id = findLocationId(AD_CODE_USER, location);
		    if (id !== null) {
		        LOCATION_ID_USER = id;
		        // console.log('LOCATION_ID_USER:', LOCATION_ID_USER);
		    } else {
		        LOCATION_ID_USER = "101010100"; // 默认北京
		    }
		    var d = 1;
		    var c = 1;
			if (result.ad_info.district !== ""){
			    d = 0;
			    document.getElementById('location_now').innerHTML = result.ad_info.district + '&nbsp;<i class="fa-solid fa-location-arrow"></i>';
			}
			else if(d && (result.ad_info.city !== "")){
			    c = 0;
			    document.getElementById('location_now').innerHTML = result.ad_info.city + '&nbsp;<i class="fa-solid fa-location-arrow"></i>';
			}
			else if(c && (result.ad_info.province !== "")){
			    document.getElementById('location_now').innerHTML = result.ad_info.province + '&nbsp;<i class="fa-solid fa-location-arrow"></i>';
			}
			else{
			    document.getElementById('location_now').innerHTML = '未知区域' + '&nbsp;<i class="fa-solid fa-location-arrow"></i>';
			}

		    // 在这里执行需要在回调函数外部进行的操作，请求并更新温度、图标代号、日落等信息到HTML中
		    getWeatherByLocationID()
			    .then(result => {
				})
			    .catch(error => console.error('Error:', error));
			
			// 在这里执行需要在回调函数外部进行的操作，请求并更新预警、代号、发布信息到HTML中
			getWarningByLocationID()			    
				.then(result => {
					// console.log(result);
					document.querySelector('alart').style.color = result.severityColor;
					// document.getElementById('alart').style.fontFamily = 'PingFangSC-Regular,Arial,sans-serif';
				})
			    .catch(error => console.log('当前无预警信息！'));
				
				
			// 在这里执行需要在回调函数外部进行的操作，请求并实时信息到HTML中
			getNowByLocationID()			    
				.then(result => {
					// console.log(result);
					document.getElementById('temp_now').innerHTML = result.temp + '℃<br>';
					document.getElementById('text_now').innerHTML = result.text + '/' + result.windDir;
					if(sunpool.includes(result.icon)){
						document.getElementById('img_weather').style.background = 'url("./src/images/27.svg")';
						
					}
					else if(rainpool.includes(result.icon)){
						document.getElementById('img_weather').style.background = 'url("./src/images/26.svg")';
					}
					else if(snowpool.includes(result.icon)){
						document.getElementById('img_weather').style.background = 'url("./src/images/28.svg")';
					}
					else if(smoggypool.includes(result.icon)){
						document.getElementById('img_weather').style.background = 'url("./src/images/30.svg")';
					}
					else if(thundpool.includes(result.icon)){
					    document.getElementById('img_weather').style.background = 'url("./src/images/31.svg")'
					}
					else{
						document.getElementById('img_weather').style.background = 'url("./src/images/29.svg")';
					}
				})
			    .catch(error => console.log('当前查询不到信息！请联系服务管理员:https://pic.ffnb.top'));
			
			
		    //在映射表里寻找Location ID
		    // function findLocationId(adCodeUser, location) {
		    //     for (const [key, values] of Object.entries(location)) {
		    //         for (const value of values) {
		    //             if (value.toString() === adCodeUser.toString()) {
		    //                 // console.log('Found matching key:', key);
		    //                 return key; // 返回第一个匹配的键
		    //             }
		    //         }
		    //     }
		    //     console.log('No match found.');
		    //     return null; // 如果没有找到匹配项，则返回null
		    // }
			function findLocationId(adCodeUser, locationMap) {
			    for (const [key, values] of Object.entries(locationMap)) {
			        if (values.includes(adCodeUser.toString())) {
			            return key;
			        }
			    }
			    console.log('No match found.');
			    return null;
			}
		}

		// 通过Location ID来请求天气
		async function getWeatherByLocationID() {
			const cityID = LOCATION_ID_USER;
			//请求温度、图标代号、日落等信息
			const url_temp = `https://devapi.qweather.com/v7/weather/3d?location=${cityID}&key=${currentKey}`;
			console.log(url_temp);
			   try {
			        const response = await fetch(url_temp, {
			            headers: {
			                'Accept-Encoding': 'gzip, deflate, br, zstd' // 表明客户端接受GZIP压缩的数据
			            }
			        });
			        if (!response.ok) {
			            throw new Error(`HTTP error! status: ${response.status}`);
			        }
			        // 读取响应体为文本
			        const text = await response.text();
			        // 解析文本为JSON对象
			        const data_temp = JSON.parse(text);
			        // 提取第一个元素中的所需数据	
					for (let i = 0; i < 3 ;i ++){
						const daily = data_temp.daily[i];
						const sunset = daily.sunset;
						const tempMax = daily.tempMax;
						const tempMin = daily.tempMin;
						const textDay = daily.textDay;
						const textNight = daily.textNight;
						const iconDay = daily.iconDay;
						const iconNight = daily.iconNight;
						if (i == 0){
							document.getElementById('today_range').innerHTML = tempMin + '~' + tempMax + '℃';
							// 获取当前时间以判断用夜间还是白天天气图标
							const now = new Date();
							const currentTime = now.getHours() * 60 + now.getMinutes();
							const sunsetTime = parseInt(sunset.split(':')[0]) * 60 + parseInt(sunset.split(':')[1]);
							// 判断是否已经是夜晚
							const isNight = currentTime > sunsetTime;
							// 使用正确的图标
							const icon = isNight ? iconNight : iconDay;
							// document.getElementById('today_range_i').innerHTML = `<i class="qi-${icon}-fill" style="font-size: 30px;">`;
							document.getElementById('today_range_i').src = `src/downloaded_images/${icon}.png`;
						}
						if (i == 1){
							document.getElementById('tomorrow_range').innerHTML = tempMin + '~' + tempMax + '℃';
							// 获取当前时间以判断用夜间还是白天天气图标
							const now = new Date();
							const currentTime = now.getHours() * 60 + now.getMinutes();
							const sunsetTime = parseInt(sunset.split(':')[0]) * 60 + parseInt(sunset.split(':')[1]);
							// 判断是否已经是夜晚
							const isNight = currentTime > sunsetTime;
							// 使用正确的图标
							const icon = isNight ? iconNight : iconDay;
						// 	document.getElementById('tomorrow_range_i').innerHTML = `<i class="qi-${icon}-fill" style="font-size: 30px;">`;
							document.getElementById('tomorrow_range_i').src = `src/downloaded_images/${icon}.png`;
						}
						if (i == 2){
							document.getElementById('day_after_tomorrow_range').innerHTML = tempMin + '~' + tempMax + '℃';
							// 获取当前时间以判断用夜间还是白天天气图标
							const now = new Date();
							const currentTime = now.getHours() * 60 + now.getMinutes();
							const sunsetTime = parseInt(sunset.split(':')[0]) * 60 + parseInt(sunset.split(':')[1]);
							// 判断是否已经是夜晚
							const isNight = currentTime > sunsetTime;
							// 使用正确的图标
							const icon = isNight ? iconNight : iconDay;
							// document.getElementById('day_after_tomorrow_range_i').innerHTML = `<i class="qi-${icon}-fill" style="font-size: 30px;">`;
							document.getElementById('day_after_tomorrow_range_i').src = `src/downloaded_images/${icon}.png`;
						}
						else{							
							console.log('TODAY + TOMORROW + DAY_AFTER_TOMORROW');
						}
					}
					// 返回结果
					return 'OK';
			    } catch (error) {
			        console.error('Error fetching and processing data:', error);
			        throw error;
			    }
		    // console.log('AD_CODE_USER:', AD_CODE_USER);
		    //  console.log('LOCATION_ID_USER:', LOCATION_ID_USER);
		}
		
		// 通过Location ID来请求预警
		async function getWarningByLocationID() {
			const cityID = LOCATION_ID_USER;
			//请求预警、代号、发布信息
			const url_warning = `https://devapi.qweather.com/v7/warning/now?location=${cityID}&key=${currentKey}`;
			console.log(url_warning);
			try {
				const response = await fetch(url_warning, {
					headers: {
						'Accept-Encoding': 'gzip, deflate, br, zstd' // 表明客户端接受GZIP压缩的数据
					}
				});
				if (!response.ok) {
					throw new Error(`HTTP error! status: ${response.status}`);
				}
				 // 读取响应体为文本
				const text_warning = await response.text();
				 // 解析文本为JSON对象
				const data_02 = JSON.parse(text_warning);
				// 提取所需的字段
				const warning = data_02.warning[0];
				if(warning != null || warning == ''){
					const pubTime = warning.pubTime;
					const type = warning.type;
					const severityColor = warning.severityColor;
					const typeName = warning.typeName;
					const startTime = warning.startTime;
					const endTime = warning.endTime;
					if (typeName.length >= 3){
						const typeName_new = typeName.substring(0,4);
						document.getElementById('alert').innerHTML = `&nbsp;<i class="qi-${type}" >&nbsp;` + typeName_new + '...';
						document.getElementById('alert_new').innerHTML = `&nbsp;<i class="qi-${type}" >&nbsp;` + typeName + '预警';
						var element = document.getElementById('alert');
						var alertNew = document.getElementById('alert_new');
						// 给触发元素添加 touchstart 和 mouseover 事件监听器
						element.addEventListener('touchstart', function() {
						  alertNew.style.display = 'block';
						  alertNew.style.backgroundColor = warning.severityColor;
						});
						element.addEventListener('mouseover', function() {
						  alertNew.style.display = 'block';
						  document.getElementById('alert_new').style.backgroundColor = warning.severityColor;
						});
						// 同样给触发元素添加 touchend 和 mouseout 事件监听器
						element.addEventListener('touchend', function() {
						  alertNew.style.display = 'none';
						  alertNew.style.backgroundColor = '';
						});
						element.addEventListener('mouseout', function() {
						  alertNew.style.display = 'none';
						  document.getElementById('alert_new').style.backgroundColor = warning.severityColor;

						});
					}
					else{
						document.getElementById('alert').innerHTML = `&nbsp;<i class="qi-${type}" >&nbsp;` + typeName + '预警';
					}
					document.getElementById('alert').style.backgroundColor = warning.severityColor;
					
					
					 // 返回结果
					return { pubTime,type,typeName,severityColor,startTime,endTime };
				 }
				 else{
					 document.getElementById('alert').innerHTML ='&nbsp;<i class="fa-regular fa-circle-check" id="spanalert">&nbsp;</i><strong>无预警</strong>&nbsp;';
					 return null;
				 }
			 } catch (error) {
				 console.error('Error fetching and processing data:', error);
				 throw error;
			 }
		}
		
		// 通过Location ID来请求实时数据
		async function getNowByLocationID() {
			const cityID = LOCATION_ID_USER;
			//请求实时信息
			const url_now = `https://devapi.qweather.com/v7/weather/now?location=${cityID}&key=${currentKey}`;
			console.log(url_now);
			try {
				 const response = await fetch(url_now, {
					 headers: {
						 'Accept-Encoding': 'gzip, deflate, br, zstd' // 表明客户端接受GZIP压缩的数据
					 }
				 });
				 if (!response.ok) {
					 throw new Error(`HTTP error! status: ${response.status}`);
				 }
				 // 读取响应体为文本
				const text_now = await response.text();
				 // 解析文本为JSON对象
				const data_now = JSON.parse(text_now);
				// 提取所需的字段
				const now = data_now.now;
				if(now != null){
					const temp = now.temp;
					const icon = now.icon;
					const text = now.text;
					const windDir = now.windDir;
					// document.getElementById('temp_icon').innerHTML = `<i class="qi-${icon}-fill" style="font-size: 35px;">`
					document.getElementById('temp_icon').innerHTML = `<img src="src/downloaded_images/${icon}.png" width="55px" alt="temp_icon">`;
					return { temp,text,windDir,icon };
				 }
				 else{
					 return null;
				 }
			 } catch (error) {
				 console.error('Error fetching and processing data:', error);
				 throw error;
			 }
		}
		
		
		// 加载JSONP（JSON with Padding）数据的简单函数
		function loadJSONP(url) {
		    const script = document.createElement('script');
		    script.src = url;
		    document.head.appendChild(script);
		}
		
		// 确保回调函数可以在全局作用域中被找到
		window.QQmap = QQmap;
		
		// 在这里调用loadJSONP函数，并传入API URL
		loadJSONP('https://apis.map.qq.com/ws/location/v1/ip?ip=&key=[]&output=jsonp&callback=QQmap');

		// // 在页面加载完成后执行函数
		window.onload = function () {
			getRandomKey();
			

		};
		
		// //获取用户IP
		// function getUserIP(callback) {
		//   var xhr = new XMLHttpRequest();
		//   xhr.open('GET', 'https://api.ipify.org?format=json', true);
		//   xhr.onreadystatechange = function() {
		// 	if (xhr.readyState === 4) {
		// 	  if(xhr.status === 200) {
		// 		var ip = JSON.parse(xhr.responseText).ip;
		// 		callback(ip);
		// 	  }
		// 	}
		//   };
		//   xhr.send();
		// }